import datetime

from sqlalchemy import Column, Integer, String, DateTime, Boolean, func

from common.db.database import Base
from common.schema import taobao as taobao_schema


class Order(Base):
    __tablename__ = "order"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(String, comment='下单id')
    android_ip = Column(String, index=True, comment='安卓手机ip')
    user_name = Column(String, comment='淘宝账号用户名')
    user_phone = Column(String, comment='淘宝账号用户名')
    password = Column(String, comment='淘宝账号密码')
    payment_password = Column(String, comment='淘宝账号支付密码')
    phone_code = Column(String, default='', comment='手机验证码')
    need_phone_code = Column(Boolean, default=False, comment='是否需要手机验证码')
    sub_name = Column(String, comment='商品子类目')
    shop_url = Column(String, comment='淘宝商品链接')
    shop_name = Column(String, comment='淘宝商品名称')
    status = Column(String, default='', comment='订单状态')
    complete = Column(Boolean, default=False, comment='是否已经付款')
    processing = Column(Boolean, default=False, comment='线程正在运行')
    order_number = Column(String, default='', comment='订单编号')
    create_time = Column(DateTime, server_default=func.now(), comment='创建时间')
    # onupdate设置自动更改
    update_time = Column(DateTime, server_default=func.now(), onupdate=func.now(), comment='修改时间')

    def to_dict(self):
        data = {c.name: getattr(self, c.name, None) for c in self.__table__.columns}
        for key, value in data.items():
            if isinstance(value, datetime.datetime):
                data[key] = str(value)
        return data

    @property
    def to_obj(self):
        return taobao_schema.TaoBaoOrderTaskResponse(**self.to_dict())
